<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Domain;
use App\Models\NewSkin;
use App\Models\Group;
use App\Models\Term;
use App\Models\Templates;
use App\Models\Query;
use App\Models\Originate;
use App\Models\CopyWechat;
use DB;
use Illuminate\Support\Facades\Redis;

class ApiController extends Controller
{

    //更新阅读状态
    public function smsUpdateStatus(Request $request){
        if($request->isMethod('post')){
           $objTb = DB::table('smsends');
           $sms_id =  $request->get('sms_id');//来源
           $res = $objTb->where('id',$sms_id)->update(['status' => 2]);
           echo json_encode(['id'=>$sms_id,"msg"=>'success']);
        }
    }

    public function index(){
        // echo "hello";
        // phpinfo();
        $data = [
            ['name'=>'Long18','age'=>18],
            ['name'=>'Long20','age'=>20],
            ['name'=>'Long22','age'=>22],
            ['name'=>'Long24','age'=>24],
        ];
        Redis::set('name', $data);
        $values = Redis::get('name');
        dd($values);
        //输出："guwenjie"
        //加一个小例子比如网站首页某个人员或者某条新闻日访问量特别高，可以存储进redis，减轻内存压力
        
    }
    /*** 来源统计 ****/
    public function originate(Request $request){
        $tag                    = new Originate();
        $tag->originate         = $request->get('originate');//来源
        $tag->url               = $request->get('url');//url
        $tag->uid               = $request->get('uid')==null?1:(int)$request->get('uid');//
        $tag->status            = $request->get('status')==null?0:(int)$request->get('status');//状态
        $tag->site_name         = $request->get('site_name');//站点名称
        $tag->wechat            = $request->get('wechat');//微信
        // $tag->touch             = $request->get('touch');//点击事件
        $tag->channel           = $request->get('channel');//渠道
        $tag->medium            = $request->get('medium');//媒体
        $tag->adverti_name      = $request->get('adverti_name');//广告名称
        $tag->adverti_content   = $request->get('adverti_content');//广告内容
        $tag->keyword           = $request->get('keyword');//关键词
        $skeyword = $request->get('skeyword');
        if(strstr($skeyword,'%')){
            $skeyword = urldecode($skeyword);
        }
        $tag->touch             = $skeyword ;//搜索词

        $tag->terminal          = $request->get('terminal');//终端
        $tag->in_wechat         = $request->get('in_wechat')==null?0:(int)$request->get('in_wechat');//是否在微信内，0:否，2:是
        $tag->adverti_type      = $request->get('adverti_type')==null?1:(int)$request->get('adverti_type');//形式，1：微信
        $tag->city              = $request->get('city');//城市
        $tag->ip                = $request->get('ip')==null?GetIp():$request->get('ip');//ip
        $tag->user_agent        = $request->get('user_agent');//浏览器类型
        $tag->domain            = $request->get('domain');//域名
        $tag->created_at        = date('Y-m-d H:i:s');
        $tag->updated_at        = date('Y-m-d H:i:s');
                
        $tag->idfa              = $request->get('idfa');//IDFA
        $tag->imei              = $request->get('imei');//IMEI
        $tag->device_id         = $request->get('device_id');//DEVICE_ID
        $tag->save();
        // $result                 = $tag->save();
        // if($result==1){
        //     echo json_encode(['status'=>200,"msg"=>'success']);
        // }else{
        //     echo json_encode(['status'=>201,"msg"=>'error']);
        // }
        echo json_encode(['status'=>200,"msg"=>'success201808']);
    }

    public function originate2(Request $request){
        $tag                    = new Originate();
        $data['originate']     = $request->get('originate');//来源
        $data['url']     = $request->get('url');//url
        $data['uid']     = $request->get('uid')==null?1:(int)$request->get('uid');//
        $data['status']     = $request->get('status')==null?0:(int)$request->get('status');//状态
        $data['site_name']     = $request->get('site_name');//站点名称
        $data['wechat']     = $request->get('wechat');//微信
        // $data['touch']     = $request->get('touch');//点击事件
        $data['channel']     = $request->get('channel');//渠道
        $data['medium']     = $request->get('medium');//媒体
        $data['adverti_name']     = $request->get('adverti_name');//广告名称
        $data['adverti_cont']   = $request->get('adverti_content');//广告内容
        $data['keyword']     = $request->get('keyword');//关键词
        $skeyword = $request->get('skeyword');
        if(strstr($skeyword,'%')){
            $skeyword = urldecode($skeyword);
        }
        $data['touch']     = $skeyword ;//搜索词

        $data['terminal']     = $request->get('terminal');//终端
        $data['in_wechat']     = $request->get('in_wechat')==null?0:(int)$request->get('in_wechat');//是否在微信内，0:否，2:是
        $data['adverti_type']     = $request->get('adverti_type')==null?1:(int)$request->get('adverti_type');//形式，1：微信
        $data['city']     = $request->get('city');//城市
        $data['ip']     = $request->get('ip')==null?GetIp():$request->get('ip');//ip
        $data['user_agent']     = $request->get('user_agent');//浏览器类型
        $data['domain']     = $request->get('domain');//域名
        $data['created_at']     = date('Y-m-d H:i:s');
        $data['updated_at']     = date('Y-m-d H:i:s');
                
        $data['idfa']     = $request->get('idfa');//IDFA
        $data['imei']     = $request->get('imei');//IMEI
        $data['device_id']     = $request->get('device_id');//DEVICE_ID

        $dataAll[] = $data;

        $result                 = $tag->save();
        if($result==1){
            echo json_encode(['status'=>200,"msg"=>'success']);
        }else{
            echo json_encode(['status'=>201,"msg"=>'error']);
        }
        echo json_encode(['status'=>200,"msg"=>'success']);
    }

    /*** CopyWechat统计 ****/
    public function copywechat(Request $request){
        $obj                    = new CopyWechat();
        $obj->uid               = $request->get('uid')==null?1:(int)$request->get('uid');//
        $obj->channel           = $request->get('channel');//渠道
        $obj->domain            = $request->get('domain');//域名
        $obj->keyword           = $request->get('keyword');//关键词
        $obj->skeyword           = $request->get('skeyword');//搜索词
        $obj->referer_url       = $request->get('referer_url');//来源
        $obj->visit_url         = $request->get('visit_url');//url
        $obj->kfwx          = $request->get('kfwx');//微信
        $obj->template          = $request->get('template');//页面模板
        $obj->ip                = $request->get('ip')==null?GetIp():$request->get('ip');//ip
        $obj->user_agent        = $request->get('user_agent');//浏览器类型
        $obj->terminal          = $request->get('terminal');//终端
        $obj->city              = $request->get('city');//城市
        $obj->created_at        = date('Y-m-d H:i:s');
        $obj->updated_at        = date('Y-m-d H:i:s');
        $obj->yeard        = date('Y');
        $obj->dated        = date('Y-m-d');
        $obj->timed        = date('H');
        $obj->idfa              = $request->get('idfa');//IDFA
        $obj->imei              = $request->get('imei');//IMEI
        $obj->device_id         = $request->get('device_id');//DEVICE_ID
        $result                 = $obj->save();
        if($result==1){
            echo json_encode(['status'=>200,"msg"=>'success']);
        }else{
            echo json_encode(['status'=>201,"msg"=>'error']);
        }
    }



    /*** 疑惑留言 qhZpxDzcigiLjttmHHrAXcfdkYf9GCul ****/
    public function query(Request $request,$uid=0){
        if($request->isMethod('post')){
            /* if($request->get('phone')==''||$request->get('phone')==null){
                echo "请输入手机号!";
            }else{ */
                $query          = new Query();
                $query->originate = $request->get('originate');//来源
                $query->user_agent= $request->get('user_agent');//浏览器类型
                $query->terminal= $request->get('terminal');//终端
                $query->name    = $request->get('name');//姓名？
                $query->phone   = $request->get('phone');//手机
                $query->query   = $request->get('query');//留言
                $query->uid     = $request->get('uid')==null?1:(int)$request->get('uid');//推广员id
                $query->wx      = $request->get('wx');//用户微信
                $query->domain  = $request->get('domain');//域名
                $query->qq      = $request->get('qq');//qq
                $query->email   = $request->get('email');//邮箱
                $query->channel = $request->get('channel');//渠道
                $query->city    = $request->get('city');//城市
                $query->title   = $request->get('title');//网页标题
                $query->nick    = $request->get('nick');//昵称
                $query->suffix  = $request->get('suffix');//路径
                $query->kfwx    = $request->get('kfwx');//客服微信
                $query->ip      = $request->get('ip')==null?GetIp():$request->get('ip');//ip
                $result         = $query->save();
                //发送短信
                if($result==1){
                    $smsTmpId = 193601;
                    $mobile = config('app.debug') ? "13694236191" :$query->phone;
                    //加入计划监控
                    $objTb = DB::table('smsends');
                    $nowTime = date('Y-m-d H:i:s',time());
                    $item = array();
                    $item['name'] = $query->name;
                    $item['phone'] = $query->phone;
                    $item['channel'] = $query->channel;
                    $item['domain'] = $query->domain;
                    $item['kfwx'] = $query->kfwx;
                    $item['created_at'] = $nowTime;
                    $item['updated_at'] = $nowTime;

                     if($request->get('age') != 18 ){
                        if($request->get('age') == 20){
                            $item['status'] = 5;
                        }else{
                            $item['status'] = 1;
                        }
                         
                     }else{
                         $item['status'] = 4;
                     }
                    $id = $objTb->where('phone',$item['phone'])->value('id');
                    if(!$id){
                      $objTb->insert($item);
                      $id = $objTb->where('phone',$item['phone'])->value('id');
                    }else{
                        $objTb->where('id',$id)->update($item);
                    }
                     // Version 1.0
                    // sendSMS($mobile,array($query->name,'http://ljh.lvtop8.com/s/?wx='.$query->kfwx.'-'.$id),$smsTmpId);

                    // 查看她的朋友圈中有惊喜，她微信号：nlgcdn901
                    
                    if($request->get('age') != 18 && $request->get('age') != 20){
                        $mainContent = "加她为好友领取>她微信号：" . $query->kfwx;
                        sendSMS($mobile,array($query->name,$mainContent),$smsTmpId);
                        echo json_encode(['status'=>200,'id'=>$id,"msg"=>'success']);
                    }
                    
                }else{
                    echo json_encode(['status'=>201,"msg"=>'error']);
                }
            //}
        }elseif($request->isMethod('get')){

            $data['uid']    = $uid;//用户id
            return view('api.query', $data);
        }
    }
    
    public function updateTemplate(Request $request){
        $domainInfo     = Domain::find($request->did);
        $objGroup       = new Term();
        $html           = $objGroup->getConfig($domainInfo->gid,$request->did,$request->tid);
        //获取模板源码
        $teplateCode    = NewSkin::where('token',$request->token)->where('filename',$request->filename)->value('html');
        if($teplateCode !== NULL){
            $html       .= $teplateCode;
        }else{
            $html       = "";
        }
        echo $html;
    }
    public function upgradeTemplate(Request $request){
        $domainInfo = Domain::find($request->did);
        $objGroup = new Group();
        $html = $objGroup->getConfig($domainInfo->gid,$request->did);
        //获取模板源码
        $teplateCode= NewSkin::where('token',$request->token)/* ->where('filename',$request->filename) */->value('html');
        //file_put_contents('upgradeTemplate.txt',$request->token);
        if($teplateCode !== NULL){
            $html .= $teplateCode;
            /*switch ($domainInfo->go_to_type){
                case 1:
                    $domainAttr = Domain::where('gid','=',$domainInfo->target_gid)->lists('domain');
                    $html .= '<script type="text/javascript">';
                    $html .= 'function goPAGE() { ';
                    $html .= 'if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) { ';
                    //如果终端是手机版本就进行跳转
                    $html .= 'var randDomain = '.collect($domainAttr).';';
                    $html .= 'var id = Math.floor(Math.random()*'.count($domainAttr).');';
                    $html .= 'window.location.href="http://"+randDomain[id];';
                    $html .= '}}';
                    $html .= '</script>';
                    break;
                case 2:
                    $domainAttr = Domain::where('gid','=',$domainInfo->target_gid)->lists('domain');
                    $html = '<script type="text/javascript">';
                    $html .= 'var randDomain = '.collect($domainAttr).';';
                    $html .= 'var id = Math.floor(Math.random()*'.count($domainAttr).');';
                    $html .= 'window.location.href="http://"+randDomain[id];';
                    $html .= 'goPAGEJ();';
                    $html .= '</script>';
                    break;
                default:
                    break;
            }*/
        }else{
            $html = "";
        }
        
        echo $html;
    }

    public function upgradeCompanyTemplate(Request $request){
        $domainInfo = Domain::find($request->did);
        $objGroup = new Group();
        $html = "";
        $html = $objGroup->getConfig($domainInfo->gid,$request->did,true);
        /*$html = trim(preg_replace('/<\?php(.*?)\?>/si','',$html));*/
        //获取模板源码
        $teplateCode= NewSkin::where('token',$request->token)->value('html');
        if($teplateCode !== NULL){
            $html .= $teplateCode;
            /*switch ($domainInfo->go_to_type){
                case 1:
                    $domainAttr = Domain::where('gid','=',$domainInfo->target_gid)->lists('domain');
                    $html .= '<script type="text/javascript">';
                    $html .= 'function goPAGE() { ';
                    $html .= 'if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) { ';
                    //如果终端是手机版本就进行跳转
                    $html .= 'var randDomain = '.collect($domainAttr).';';
                    $html .= 'var id = Math.floor(Math.random()*'.count($domainAttr).');';
                    $html .= 'window.location.href="http://"+randDomain[id];';
                    $html .= '}}';
                    $html .= 'goPAGEJ();';
                    $html .= '</script>';
                    break;
                case 2:
                    $domainAttr = Domain::where('gid','=',$domainInfo->target_gid)->lists('domain');
                    $html = '<script type="text/javascript">';
                    $html .= 'var randDomain = '.collect($domainAttr).';';
                    $html .= 'var id = Math.floor(Math.random()*'.count($domainAttr).');';
                    $html .= 'window.location.href="http://"+randDomain[id];';
                    $html .= 'goPAGEJ();';
                    $html .= '</script>';
                    break;
                default:
                    break;
            }*/
        }else{
            $html = "";
        }
        echo $html;
    }
}
